<template>
  <Form ref="formRef" :model="formParams">
    <Row>
      <Col span="5">
        <FormItem label="结算日期" :label-width="100">
          <RadioGroup v-model="chooseDate" type="button" @change="changeDate" button-style="solid">
            <Radio label="年"></Radio>
            <Radio label="半年"></Radio>
            <Radio label="季度"></Radio>
            <Radio label="月"></Radio>
          </RadioGroup>
        </FormItem>
      </Col>
      <Col span="4">
        <FormItem :label-width="50">
          <el-date-picker
            v-if="chooseDate === '年'"
            v-model="settlementDate"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="year"
            placeholder="选择年"
          />
          <HalfYearPicker
            v-model="settlementDate"
            :placeholder="'选择半年'"
            v-if="chooseDate === '半年'"
          />
          <QuarterPicker
            v-model="settlementDate"
            :placeholder="'选择季度'"
            v-if="chooseDate === '季度'"
          />

          <el-date-picker
            v-if="chooseDate === '月'"
            v-model="settlementDate"
            type="month"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择月"
          />
        </FormItem>
      </Col>
      <Col span="4">
        <FormItem label="院区" prop="areaID">
          <Select v-model="formParams.areaID" style="width: 200px" @on-change="areaChg">
            <Option v-for="item in area" :value="item.areaID" :key="item.areaID">{{
              item.name
            }}</Option>
          </Select>
        </FormItem>
      </Col>
      <!-- <Col span="4" v-if="policy === 'DRG'">
        <FormItem label="科室" prop="categoryID">
          <TreeSelect
            :data="treeList.data"
            @on-change="treeChg"
            v-model="formParams.categoryID"
            multiple
            style="width: 200px"
          >
          </TreeSelect>
        </FormItem>
      </Col> -->

      <Col span="4">
        <Space style="margin-left: 20px">
          <Button type="primary" icon="md-search" @click="goSearch">查询</Button>
          <Button type="dashed" icon="md-refresh" @click="clear">重置</Button>
        </Space>
      </Col>
    </Row>
  </Form>
  <Row gutter="20" align="middle">
    <Col :span="17" style="margin-bottom: 20px">
      <div style="display: flex; align-items: center">
        <div style="width: 4px; height: 22px; background-color: #409eff; margin-right: 5px"></div>
        <h2 style="color: #409eff">{{ policy === 'DRG' ? 'DRG' : 'DIP' }}付费病例</h2>
      </div>
    </Col>
    <Col :span="6" style="margin-bottom: 20px">
      <div style="display: flex; align-items: center">
        <div style="width: 4px; height: 22px; background-color: #409eff; margin-right: 5px"></div>
        <h2 style="color: #409eff">其他病例</h2>
      </div>
    </Col>
    <Col span="3">
      <Card>
        <div style="text-align: center">
          <Tag size="large" color="green">{{ policy == 'DIP' ? '总点数' : '总权重' }}</Tag>
          <div></div>
          <CountUp :end="userInfo.zqz" :decimals="2" ref="count" v-font="24" />
          <span style="margin-left: 5px">百万</span>
        </div>
      </Card>
    </Col>

    <Col span="3">
      <Card>
        <div style="text-align: center">
          <Tag size="large" color="cyan">病例数（个） </Tag>
          <div></div>
          <CountUp :end="userInfo.bls_str" :duration="2" ref="count" v-font="24" />
          <span style="margin-left: 5px">{{ filterUnit(userInfo.bls_str) }}</span>
          <Progress
            :percent="userInfo.bls_per"
            :stroke-width="20"
            status="active"
            text-inside
            :stroke-color="['#13C2C2', '#13C2C2']"
          />
        </div>
      </Card>
    </Col>
    <Col span="3">
      <Card>
        <div style="text-align: center">
          <Tag size="large" color="blue">医疗总费用（元）</Tag>
          <div></div>
          <CountUp
            :end="userInfo.zfy > 10000 ? userInfo.zfy / 10000 : userInfo.zfy"
            :duration="2"
            :decimals="2"
            ref="count"
            v-font="24"
          />
          <span style="margin-left: 5px">{{
            userInfo.zfy && userInfo.zfy > 10000 ? '万' : ''
          }}</span>
          <Progress
            :percent="userInfo.zfy_per"
            :stroke-width="20"
            status="active"
            text-inside
            :stroke-color="['#1890FF', '#1890FF']"
          />
        </div>
      </Card>
    </Col>
    <Col span="3">
      <Card>
        <div style="text-align: center">
          <Tag size="large" color="geekblue">支付差额（元）</Tag>
          <div></div>
          <CountUp :end="userInfo.zfc" :duration="2" ref="count" v-font="24" />
          <span style="margin-left: 5px">{{ filterUnit(userInfo.zfc_str) || '百万' }}</span>
        </div>
      </Card>
    </Col>
    <Col span="3">
      <Card>
        <div style="text-align: center">
          <Tag size="large" color="purple">拨付比 </Tag>
          <div></div>
          <CountUp :end="userInfo.bfb" :duration="2" ref="count" v-font="24" />
          <span style="margin-left: 5px">%</span>
        </div>
      </Card>
    </Col>
    <Col span="2"> </Col>
    <Col span="3">
      <Card>
        <div style="text-align: center">
          <Tag size="large" color="magenta">病例数（个）</Tag>
          <div></div>
          <CountUp :end="userInfo.other_bls" :duration="2" ref="count" v-font="24" />
          <span style="margin-left: 5px">{{ filterUnit(userInfo.other_bls_str) }}</span>
          <Progress
            :percent="userInfo.other_bls_per"
            :stroke-width="20"
            status="active"
            text-inside
            :stroke-color="['#EB2F96', '#EB2F96']"
          />
        </div>
      </Card>
    </Col>
    <Col span="3">
      <Card>
        <div style="text-align: center">
          <Tag size="large" color="#17B81D">医疗总费用（元）</Tag>
          <div></div>
          <CountUp :end="userInfo.other_zfy" :duration="2" ref="count" v-font="24" />
          <span style="margin-left: 5px">{{ filterUnit(userInfo.other_zfy_str) || '万' }}</span>
          <Progress
            :percent="userInfo.other_zfy_per"
            :stroke-width="20"
            status="active"
            text-inside
            :stroke-color="['#17B81D', '#17B81D']"
          />
        </div>
      </Card>
    </Col>
  </Row>
  <Row style="padding-top: 30px">
    <Col span="24" style="margin-bottom: 20px">
      <div style="display: flex; align-items: center">
        <div style="width: 4px; height: 22px; background-color: #409eff; margin-right: 5px"></div>
        <h2 style="color: #409eff">医疗费用分析</h2>
      </div>
    </Col>
    <Col span="24" style="margin-bottom: 20px">
      <div class="chart-container">
        <el-card style="width: 49%">
          <div class="chart-header">
            <h3>总费用与支付差趋势图</h3>
            <el-button type="primary" link @click="seeMore('line1')">查看更多</el-button>
          </div>
          <div style="width: 100%; height: 350px" id="line1"></div>
        </el-card>
        <el-card style="width: 49%">
          <div class="chart-header">
            <h3>不同医保类型盈亏趋势</h3>
            <el-button type="primary" link @click="seeMore('line2')">查看更多</el-button>
          </div>
          <div style="width: 90%; height: 350px" id="line2"></div>
        </el-card>
      </div>
    </Col>
    <Col span="24" style="margin-bottom: 20px">
      <div class="chart-container">
        <el-card style="width: 49%">
          <div class="chart-header">
            <h3>费用结构</h3>
            <el-button type="primary" link @click="seeMore('line3')">查看更多</el-button>
          </div>
          <div style="width: 100%; height: 350px" id="line3"></div>
        </el-card>
        <el-card style="width: 49%">
          <div class="chart-header">
            <h3>总病例数与入组率趋势</h3>
            <el-button type="primary" link @click="seeMore('line4')">查看更多</el-button>
          </div>
          <div style="width: 100%; height: 350px" id="line4"></div>
        </el-card>
      </div>
    </Col>
  </Row>

  <Row style="padding-top: 30px">
    <Col span="24" style="margin-bottom: 20px">
      <div style="display: flex; align-items: center">
        <div style="width: 4px; height: 22px; background-color: #409eff; margin-right: 5px"></div>
        <h2 style="color: #409eff">医疗服务能力评价</h2>
      </div>
    </Col>
    <Col span="24" style="margin-bottom: 20px">
      <div class="chart-container">
        <el-card style="width: 49%">
          <div class="chart-header">
            <h3>总病例数与入组率趋势</h3>
            <el-button type="primary" link @click="seeMore('line5')">查看更多</el-button>
          </div>
          <div style="width: 100%; height: 350px" id="line5"></div>
        </el-card>
        <el-card style="width: 49%">
          <div class="chart-header">
            <h3>四级手术占比及数量趋势</h3>
            <el-button type="primary" link @click="seeMore('line6')">查看更多</el-button>
          </div>
          <div style="width: 100%; height: 350px" id="line6"></div>
        </el-card>
      </div>
    </Col>

    <Col span="24" style="margin-bottom: 20px">
      <div class="chart-container">
        <el-card style="width: 49%">
          <div class="chart-header">
            <h3>CMI （院内+区域平均值）</h3>
            <el-button type="primary" link @click="seeMore('line7')">查看更多</el-button>
          </div>
          <div style="width: 100%; height: 350px" id="line7"></div>
        </el-card>

        <el-card style="width: 49%">
          <div class="chart-header">
            <h3>科室CMI与盈亏分布</h3>
            <el-button type="primary" link @click="seeMore('line8')">查看更多</el-button>
          </div>
          <div style="width: 100%; height: 350px" id="line8"></div>
        </el-card>
      </div>
    </Col>
  </Row>

  <Row style="padding-top: 30px">
    <Col span="24" style="margin-bottom: 20px">
      <div style="display: flex; align-items: center">
        <div style="width: 4px; height: 22px; background-color: #409eff; margin-right: 5px"></div>
        <h2 style="color: #409eff">服务效率评价</h2>
      </div>
    </Col>
    <Col span="24" style="margin-bottom: 20px">
      <div class="chart-container">
        <el-card style="width: 49%">
          <div class="chart-header">
            <h3>时间消耗指数与费用消耗指数</h3>
            <el-button type="primary" link @click="seeMore('line9')">查看更多</el-button>
          </div>
          <div style="width: 100%; height: 350px" id="line9"></div>
        </el-card>
        <el-card style="width: 49%">
          <div class="chart-header">
            <h3>平均住院日与次均费用</h3>
            <el-button type="primary" link @click="seeMore('line10')">查看更多</el-button>
          </div>
          <div style="width: 100%; height: 350px" id="line10"></div>
        </el-card>
      </div>
    </Col>
  </Row>
  <Row style="padding-top: 30px">
    <Col span="24" style="margin-bottom: 20px">
      <div style="display: flex; align-items: center">
        <div style="width: 4px; height: 22px; background-color: #409eff; margin-right: 5px"></div>
        <h2 style="color: #409eff">医疗安全相关评价</h2>
      </div>
    </Col>

    <Col span="24" style="margin-bottom: 20px">
      <div class="chart-container">
        <el-card style="width: 49%">
          <div class="chart-header">
            <h3>低风险死亡率趋势</h3>
            <el-button type="primary" link @click="seeMore('line11')">查看更多</el-button>
          </div>
          <div style="width: 100%; height: 350px" id="line11"></div>
        </el-card>

        <el-card style="width: 49%">
          <div class="chart-header">
            <h3>高低倍率病例趋势图</h3>
            <el-button type="primary" link @click="seeMore('line12')">查看更多</el-button>
          </div>
          <div style="width: 100%; height: 350px" id="line12"></div>
        </el-card>
      </div>
    </Col>
  </Row>
  <Row style="padding-top: 10px">
    <Col span="24">
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column prop="date" label="时间" width="100" align="center" />
        <el-table-column prop="totalFee" label="总费用" align="center" />
        <el-table-column prop="payFee" label="支付差" align="center" />
        <el-table-column prop="totalCases" label="总病例数" align="center" />
        <el-table-column prop="joinRate" label="入组率" align="center" />
        <el-table-column prop="totalScore" label="总分值" align="center" />
        <el-table-column prop="dipCount" label="DIP组数" align="center" />
        <el-table-column prop="cmi" label="CMI" align="center" />
        <el-table-column prop="timeIndex" label="时间消耗指数" align="center" />
        <el-table-column prop="costIndex" label="费用消耗指数" align="center" />
        <el-table-column prop="avgStay" label="平均住院日" align="center" />
        <el-table-column prop="avgCost" label="次均费用" align="center" />
        <el-table-column prop="lowRiskDeath" label="低风险死亡率" align="center" />
        <el-table-column prop="highRatio" label="高倍率病例数" align="center" />
        <el-table-column prop="lowRatio" label="低倍率病例数" align="center" />
        <el-table-column prop="fourSurgery" label="四级手术占比" align="center" />
        <el-table-column prop="threeSurgery" label="三级手术占比" align="center" />
        <el-table-column prop="daySurgery" label="日间手术占比" align="center" />
        <el-table-column prop="minimally" label="微创手术占比" align="center" />
        <el-table-column prop="totalScore" label="综合得分" align="center" />
      </el-table>
    </Col>
  </Row>

  <!-- 查看更多弹框 -->
  <more-details ref="moreDetailsRef" />
</template>
<script setup>
import { useCommonStore } from '@/stores/common.js'
const commonStore = useCommonStore()

import * as echarts from 'echarts'
import { onActivated, onMounted, onBeforeUnmount } from 'vue'
import HalfYearPicker from '../../../components/common/HalfYearPicker.vue'
import QuarterPicker from '../../../components/common/QuarterPicker.vue'

import MoreDetails from '../components/moreDetails.vue'

import moment from 'moment'
import http from '@/util/http1'
const policy = ref('')
policy.value = commonStore.getPolicy()

const chooseDate = ref('年')
let formParams = ref({
  startDate: '',
  endDate: '',
  areaID: '1',
})

const area = ref([])

const initArea = () => {
  http.get('/Basic/Area/ListByUser', {}).then((response) => {
    area.value = response.data
  })
}
initArea()

const areaChg = (areaID) => {
  formParams.areaID = areaID
}

const formatTreeData = (data) => {
  return data.map((item) => ({
    title: item.title,
    value: item.categoryID,
    expand: true,
    children: item.children ? formatTreeData(item.children) : null,
  }))
}

const userInfo = reactive({
  zqz: 0,
  bls: 0,
  bls_str: 0,
  bls_per: 0,
  zfy: 0,
  yrz: 0,
  zfy_str: 0,
  zfy_per: 0,
  zfc: 0,
  zfc_str: 0,
  bfb: 0,
  other_bls: 0,
  other_bls_str: 0,
  other_bls_per: 0,
  other_zfy: 0,
  other_zfy_str: 0,
  other_zfy_per: 0,
})

const settlementDate = ref('')
let lineChart1 = null
let lineChart2 = null
let lineChart3 = null
let lineChart4 = null
let lineChart5 = null
let lineChart6 = null
let lineChart7 = null
let lineChart8 = null
let lineChart9 = null
let lineChart10 = null
let lineChart11 = null
let lineChart12 = null

const initLine1 = () => {
  const line1 = document.getElementById('line1')
  lineChart1 = echarts.init(line1)
  updateLine1Chart()
}

const updateLine1Chart = () => {
  if (!lineChart1) return

  const option1 = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      bottom: 0,
      data: lineList1.value.legend || [],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: lineList1.value.xAxis || [],
    },
    yAxis: {
      type: 'value',
      name: '单位：万元',
      nameTextStyle: {
        padding: [0, 0, 0, 0],
        color: '#666',
      },
    },
    series: lineList1.value.series || [],
  }
  lineChart1.setOption(option1)
}

onMounted(() => {
  initLine1()
})

const initLine2 = () => {
  const line2 = document.getElementById('line2')
  lineChart2 = echarts.init(line2)
  updateLine2Chart()
}

const updateLine2Chart = () => {
  if (!lineChart2) return

  const option2 = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      bottom: 0,
      data: lineList2.value.legend || [],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: lineList2.value.xAxis || [],
    },
    yAxis: {
      type: 'value',
      name: '单位：万元',
      nameTextStyle: {
        padding: [0, 0, 0, 0],
        color: '#666',
      },
    },
    series: lineList2.value.series || [],
  }
  lineChart2.setOption(option2)
}

onMounted(() => {
  initLine2()
})

const initLine3 = () => {
  const line3 = document.getElementById('line3')
  lineChart3 = echarts.init(line3)
  updateLine3Chart()
}

const lineList3 = ref({
  data: [
    { value: 30, name: '耗材' },
    { value: 15, name: '检查检验' },
    { value: 5, name: '药品' },
    { value: 25, name: 'XX' },
    { value: 25, name: '其他' },
  ],
  legend: ['耗材', '检查检验', '药品', '其他', 'XX'],
})

const updateLine3Chart = () => {
  if (!lineChart3) return

  const option3 = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
    },
    legend: {
      bottom: 0,
      data: lineList3.value.legend || [],
    },
    series: [
      {
        name: '费用结构',
        type: 'pie',
        radius: ['50%', '70%'],
        // 修改这里，将圆环向上移动
        center: ['50%', '45%'], // 默认是 ['50%', '50%']，第二个值改小会让图表往上移
        avoidLabelOverlap: false,
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}: {d}%',
        },
        data: lineList3.value.data || [],
      },
    ],
  }
  lineChart3.setOption(option3)
}

onMounted(() => {
  initLine3()
})

const lineList4 = ref({
  xAxis: ['胸心外科', '耳鼻二科', '关节骨科', '脊柱骨科', '消化内科', '心血管科', '内分泌科'],
  legend: ['DIP支付费用', '亏损部分', '盈余部分'],
  series: [
    {
      name: 'DIP支付费用',
      type: 'bar',
      stack: '总量',
      data: [60.1, 45, 35, 30, 25, 20, 15],
    },
    {
      name: '亏损部分',
      type: 'bar',
      stack: '总量',
      data: [10.5, 0.2, 1.2, 33, 11, 33, 2],
    },
    {
      name: '盈余部分',
      type: 'bar',
      stack: '总量',
      data: [3.3, 12, 25, 7.1, 7.1, 7.1, 7.1],
    },
  ],
})

const initLine4 = () => {
  const line4 = document.getElementById('line4')
  lineChart4 = echarts.init(line4)
  updateLine4Chart()
}

const updateLine4Chart = () => {
  if (!lineChart4) return

  const option4 = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    legend: {
      data: lineList4.value.legend || [],
      bottom: 0,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: lineList4.value.xAxis || [],
    },
    yAxis: {
      type: 'value',
      name: '单位：万元',
      nameTextStyle: {
        padding: [0, 0, 0, 40],
        color: '#666',
      },
    },
    series: lineList4.value.series || [],
  }
  lineChart4.setOption(option4)
}

const filterUnit = (unitName) => {
  const units = {
    1: '元',
    2: '十',
    3: '百',
    4: '千',
    5: '万',
    6: '十万',
    7: '百万',
    8: '千万',
    9: '亿',
  }
  return units[unitName] || ''
}

onMounted(() => {
  initLine4()
})

const lineList5 = ref({
  xAxis: ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05', '2024-06'],
  legend: ['总病例数', '入组病例数', '入组率'],
  series: [
    {
      name: '总病例数',
      type: 'bar',
      data: [904, 905, 861, 676, 506, 764],
    },
    {
      name: '入组病例数',
      type: 'bar',
      data: [904, 855, 800, 532, 185, 649],
    },
    {
      name: '入组率',
      type: 'line',
      yAxisIndex: 1,
      data: [100, 95, 92, 78, 36, 85],
    },
  ],
})

const initLine5 = () => {
  const line5 = document.getElementById('line5')
  lineChart5 = echarts.init(line5)
  updateLine5Chart()
}

const updateLine5Chart = () => {
  if (!lineChart5) return

  const option5 = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      },
    },
    legend: {
      data: lineList5.value.legend || [],
      bottom: 0,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true,
    },
    xAxis: [
      {
        type: 'category',
        data: lineList5.value.xAxis || [],
      },
    ],
    yAxis: [
      {
        type: 'value',
        name: '数量（例）',
        nameTextStyle: {
          padding: [10, 0, 0, -10],
          color: '#666',
        },
      },
      {
        type: 'value',
        name: '占比（%）',
        nameTextStyle: {
          padding: [10, 0, 0, 40],
          color: '#666',
        },
        max: 100,
        min: 0,
      },
    ],
    series: [
      {
        ...lineList5.value.series[0],
        barGap: 0,
      },
      {
        ...lineList5.value.series[1],
        barGap: 0,
      },
      {
        ...lineList5.value.series[2],
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 2,
        },
      },
    ],
  }
  lineChart5.setOption(option5)
}

onMounted(() => {
  initLine5()
})

const lineList6 = ref({
  xAxis: ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05', '2024-06'],
  legend: ['全部手术', '四级手术', '四级手术占比'],
  series: [
    {
      name: '全部手术',
      type: 'bar',
      data: [904, 905, 861, 676, 506, 764],
    },
    {
      name: '四级手术',
      type: 'bar',
      data: [802, 774, 400, 532, 185, 649],
    },
    {
      name: '四级手术占比',
      type: 'line',
      yAxisIndex: 1,
      smooth: true,
      symbol: 'circle',
      symbolSize: 8,
      lineStyle: {
        width: 2,
      },
      data: [90, 85, 46, 79, 37, 85],
    },
  ],
})

const initLine6 = () => {
  const line6 = document.getElementById('line6')
  lineChart6 = echarts.init(line6)
  updateLine6Chart()
}

const updateLine6Chart = () => {
  if (!lineChart6) return

  const option6 = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      },
    },
    legend: {
      data: lineList6.value.legend || [],
      bottom: 0,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true,
    },
    xAxis: [
      {
        type: 'category',
        data: lineList6.value.xAxis || [],
      },
    ],
    yAxis: [
      {
        type: 'value',
        name: '手术量（例）',
        nameTextStyle: {
          padding: [10, 0, 0, -10],
          color: '#666',
        },
      },
      {
        type: 'value',
        name: '占比（%）',
        nameTextStyle: {
          padding: [10, 0, 0, 40],
          color: '#666',
        },
        max: 100,
        min: 0,
      },
    ],
    series: [
      {
        ...lineList6.value.series[0],
        barGap: 0,
      },
      {
        ...lineList6.value.series[1],
        barGap: 0,
      },
      {
        ...lineList6.value.series[2],
      },
    ],
  }
  lineChart6.setOption(option6)
}

onMounted(() => {
  initLine6()
})

const lineList7 = ref({
  xAxis: ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05', '2024-06'],
  legend: ['CMI值'],
  series: [
    {
      name: 'CMI值',
      type: 'line',
      symbol: 'circle',
      symbolSize: 8,
      lineStyle: {
        width: 2,
      },
      data: [0.51, 1.41, 0.76, 0.43, 1.75, 1.72],
    },
  ],
})

const initLine7 = () => {
  const line7 = document.getElementById('line7')
  lineChart7 = echarts.init(line7)
  updateLine7Chart()
}

const updateLine7Chart = () => {
  if (!lineChart7) return

  const option7 = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br />{a}: {c}',
    },
    legend: {
      data: lineList7.value.legend || [],
      bottom: 0,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: lineList7.value.xAxis || [],
    },
    yAxis: {
      type: 'value',
      name: 'CMI值',
      nameTextStyle: {
        padding: [0, 0, 0, 40],
        color: '#666',
      },
    },
    series: lineList7.value.series || [],
  }
  lineChart7.setOption(option7)
}

onMounted(() => {
  initLine7()
})

const lineList8 = ref({
  legend: ['散点'],
  series: [
    {
      type: 'scatter',
      symbolSize: 10,
      data: [
        [180, 1.8],
        [150, 1.6],
        [120, -1.5],
        [90, 1.4],
        [-160, 1.7],
        [-130, 1.5],
        [-100, -1.4],
        [-70, 1.3],
        [-140, 0.6],
        [-110, 0.5],
        [-80, 0.4],
        [-50, 0.3],
        [140, 0.7],
        [110, 0.6],
        [80, 0.5],
        [50, 0.4],
      ],
    },
  ],
})

const initLine8 = () => {
  const line8 = document.getElementById('line8')
  lineChart8 = echarts.init(line8)
  updateLine8Chart()
}

const updateLine8Chart = () => {
  if (!lineChart8) return

  const option8 = {
    tooltip: {
      trigger: 'item',
      formatter: function (params) {
        return `盈亏金额: ${params.value[0]}万元<br/>CMI值: ${params.value[1]}`
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'value',
      name: '盈亏金额（万元）',
      nameTextStyle: {
        padding: [0, 0, 0, 40],
        color: '#666',
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
        },
      },
      min: function (value) {
        return value.min < 0 ? value.min : -value.max
      },
      max: function (value) {
        return value.max > 0 ? value.max : -value.min
      },
    },
    yAxis: {
      type: 'value',
      name: 'CMI值',
      nameTextStyle: {
        padding: [0, 40, 0, 0],
        color: '#666',
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
        },
      },
      min: function (value) {
        return value.min < 0 ? value.min : -value.max
      },
      max: function (value) {
        return value.max > 0 ? value.max : -value.min
      },
    },
    series: [
      {
        ...lineList8.value.series[0],
        symbolSize: 12,
        itemStyle: {
          color: '#5470c6',
        },
        markLine: {
          silent: true,
          lineStyle: {
            color: '#333',
          },
          data: [{ xAxis: 0 }, { yAxis: 0 }],
        },
      },
    ],
  }
  lineChart8.setOption(option8)
}

onMounted(() => {
  initLine8()
})

const lineList9 = ref({
  xAxis: ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05', '2024-06'],
  legend: ['时间消耗指数', '费用消耗指数'],
  series: [
    {
      name: '时间消耗指数',
      type: 'line',
      data: [0.75, 1.4, 0.25, 1.15, 0.96, 0.1],
      itemStyle: {
        color: '#5470c6',
      },
    },
    {
      name: '费用消耗指数',
      type: 'line',
      data: [0.2, 0.55, 1.1, 1.75, 1.55, 0.85],
      itemStyle: {
        color: '#91cc75',
      },
    },
  ],
})

const initLine9 = () => {
  const line9 = document.getElementById('line9')
  lineChart9 = echarts.init(line9)
  updateLine9Chart()
}

const updateLine9Chart = () => {
  if (!lineChart9) return

  const option9 = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: lineList9.value.legend || [],
      bottom: 0,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: lineList9.value.xAxis || [],
    },
    yAxis: {
      type: 'value',
      nameTextStyle: {
        padding: [0, 0, 0, 40],
        color: '#666',
      },
    },
    series: lineList9.value.series || [],
  }
  lineChart9.setOption(option9)
}

onMounted(() => {
  initLine9()
})

const lineList10 = ref({
  xAxis: ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05', '2024-06'],
  legend: ['平均住院日', '次均费用'],
  series: [
    {
      name: '平均住院日',
      type: 'line',
      yAxisIndex: 0,
      data: [7.5, 14, 2.5, 11.5, 9.6, 1],
      itemStyle: {
        color: '#5470c6',
      },
    },
    {
      name: '次均费用',
      type: 'line',
      yAxisIndex: 1,
      data: [2000, 0.55, 1.1, 1.75, 1.55, 0.85],
      itemStyle: {
        color: '#91cc75',
      },
    },
  ],
})

const initLine10 = () => {
  const line10 = document.getElementById('line10')
  lineChart10 = echarts.init(line10)
  updateLine10Chart()
}

const updateLine10Chart = () => {
  if (!lineChart10) return

  const option10 = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      },
    },
    legend: {
      data: lineList10.value.legend || [],
      bottom: 0,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: lineList10.value.xAxis || [],
    },
    yAxis: [
      {
        type: 'value',
        name: '住院日（天）',
        nameTextStyle: {
          padding: [0, 0, 0, 40],
          color: '#666',
        },
      },
      {
        type: 'value',
        name: '费用（元）',
        nameTextStyle: {
          padding: [0, 40, 0, 0],
          color: '#666',
        },
      },
    ],
    series: lineList10.value.series || [],
  }
  lineChart10.setOption(option10)
}

onMounted(() => {
  initLine10()
})

const lineList11 = ref({
  xAxis: ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05', '2024-06'],
  legend: ['死亡病例数', '低风险死亡病例数', '死亡率', '低风险死亡率'],
  series: [
    {
      name: '死亡病例数',
      type: 'bar',
      data: [904, 905, 861, 676, 506, 764],
    },
    {
      name: '低风险死亡病例数',
      type: 'bar',
      data: [802, 774, 400, 532, 185, 649],
    },
    {
      name: '死亡率',
      type: 'line',
      yAxisIndex: 1,
      data: [90, 85, 46, 79, 37, 85],
    },
    {
      name: '低风险死亡率',
      type: 'line',
      yAxisIndex: 1,
      data: [80, 75, 36, 69, 27, 75],
    },
  ],
})

const initLine11 = () => {
  const line11 = document.getElementById('line11')
  lineChart11 = echarts.init(line11)
  updateLine11Chart()
}

const updateLine11Chart = () => {
  if (!lineChart11) return

  const option11 = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      },
    },
    legend: {
      data: lineList11.value.legend || [],
      bottom: 0,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true,
    },
    xAxis: [
      {
        type: 'category',
        data: lineList11.value.xAxis || [],
      },
    ],
    yAxis: [
      {
        type: 'value',
        name: '病例数（例）',
        nameTextStyle: {
          padding: [0, 0, 0, 40],
          color: '#666',
        },
      },
      {
        type: 'value',
        name: '占比（%）',
        nameTextStyle: {
          padding: [0, 40, 0, 0],
          color: '#666',
        },
        max: 100,
        min: 0,
      },
    ],
    series: [
      {
        ...lineList11.value.series[0],
        barGap: 0,
      },
      {
        ...lineList11.value.series[1],
        barGap: 0,
      },
      {
        ...lineList11.value.series[2],
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 2,
        },
      },
      {
        ...lineList11.value.series[3],
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 2,
        },
      },
    ],
  }
  lineChart11.setOption(option11)
}

onMounted(() => {
  initLine11()
})

const lineList12 = ref({
  xAxis: ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05', '2024-06'],
  legend: ['高倍率病例数', '低倍率病例数', '高倍率占比', '低倍率占比'],
  series: [
    {
      name: '高倍率病例数',
      type: 'bar',
      data: [904, 905, 861, 676, 506, 764],
    },
    {
      name: '低倍率病例数',
      type: 'bar',
      data: [802, 774, 400, 532, 185, 649],
    },
    {
      name: '高倍率占比',
      type: 'line',
      yAxisIndex: 1,
      data: [90, 85, 46, 79, 37, 85],
    },
    {
      name: '低倍率占比',
      type: 'line',
      yAxisIndex: 1,
      data: [80, 75, 36, 69, 27, 75],
    },
  ],
})

const initLine12 = () => {
  const line12 = document.getElementById('line12')
  lineChart12 = echarts.init(line12)
  updateLine12Chart()
}

const updateLine12Chart = () => {
  if (!lineChart12) return

  const option12 = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      },
    },
    legend: {
      data: lineList12.value.legend || [],
      bottom: 0,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true,
    },
    xAxis: [
      {
        type: 'category',
        data: lineList12.value.xAxis || [],
      },
    ],
    yAxis: [
      {
        type: 'value',
        name: '病例数（例）',
        nameTextStyle: {
          padding: [0, 0, 0, 40],
          color: '#666',
        },
      },
      {
        type: 'value',
        name: '占比（%）',
        nameTextStyle: {
          padding: [0, 40, 0, 0],
          color: '#666',
        },
        max: 100,
        min: 0,
      },
    ],
    series: [
      {
        ...lineList12.value.series[0],
        barGap: 0,
      },
      {
        ...lineList12.value.series[1],
        barGap: 0,
      },
      {
        ...lineList12.value.series[2],
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 2,
        },
      },
      {
        ...lineList12.value.series[3],
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 2,
        },
      },
    ],
  }
  lineChart12.setOption(option12)
}

onMounted(() => {
  initLine12()
})

const changeDate = (val) => {
  settlementDate.value = ''
}
const formRef = ref(null)
const clear = () => {
  chooseDate.value = '年'
  settlementDate.value = moment().startOf('year').format('YYYY-MM-DD HH:mm:ss')
  formParams.areaID = area.value[0].areaID
  formRef.value.resetFields()
}
const lineList1 = ref({
  legend: ['总收入', '支付差'],
  xAxis: ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05', '2024-06'],
  series: [
    {
      name: '总收入',
      type: 'line',
      data: [389, 672, 166, 565, 481, 41],
    },
    {
      name: '支付差',
      type: 'line',
      data: [46, 272, 534, 907, 766, 422],
    },
  ],
})
const lineList2 = ref({
  legend: ['职工', '居民', '其他'],
  xAxis: ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05', '2024-06'],
  series: [
    {
      name: '职工',
      type: 'line',
      data: [389, 672, 166, 565, 481, 41],
    },
    {
      name: '居民',
      type: 'line',
      data: [46, 272, 534, 907, 766, 422],
    },
    {
      name: '其他',
      type: 'line',
      data: [22, 333, 234, 407, 566, 922],
    },
  ],
})
const totalData = ref([])
const tableData = ref([
  {
    date: '2024-01',
    totalFee: 0,
    payFee: 0,
    totalCases: 0,
    joinRate: '0%',
    totalScore: 0,
    dipCount: 0,
    cmi: 0,
    timeIndex: 0,
    costIndex: 0,
    avgStay: 0,
    avgCost: 0,
    lowRiskDeath: '0%',
    highRatio: 0,
    lowRatio: 0,
    fourSurgery: '0%',
    threeSurgery: '0%',
    daySurgery: '0%',
    minimally: '0%',
    totalScore: 0,
  },
])
const moreDetailsRef = ref(null)
const seeMore = (type = '') => {
  moreDetailsRef.value?.open(type)
}
const goSearch = async () => {
  if (settlementDate.value) {
    if (chooseDate.value === '年') {
      formParams.value.startDate = moment(settlementDate.value)
        .startOf('year')
        .format('YYYY-MM-DD HH:mm:ss')
      formParams.value.endDate = moment(settlementDate.value)
        .endOf('year')
        .format('YYYY-MM-DD HH:mm:ss')
    } else if (chooseDate.value === '半年') {
      const [year, half] = settlementDate.value.split('-')
      if (half === '1') {
        formParams.value.startDate = moment(`${year}-01-01`).format('YYYY-MM-DD HH:mm:ss')
        formParams.value.endDate = moment(`${year}-06-30`).format('YYYY-MM-DD 23:59:59')
      } else if (half === '2') {
        formParams.value.startDate = moment(`${year}-07-01`).format('YYYY-MM-DD HH:mm:ss')
        formParams.value.endDate = moment(`${year}-12-31`).format('YYYY-MM-DD 23:59:59')
      }
    } else if (chooseDate.value === '季度') {
      const [year, quarter] = settlementDate.value.split('-')
      const quarterMap = {
        '01': { start: '01-01', end: '03-31' },
        '02': { start: '04-01', end: '06-30' },
        '03': { start: '07-01', end: '09-30' },
        '04': { start: '10-01', end: '12-31' },
      }
      const { start, end } = quarterMap[quarter]
      formParams.value.startDate = moment(`${year}-${start}`).format('YYYY-MM-DD 00:00:00')
      formParams.value.endDate = moment(`${year}-${end}`).format('YYYY-MM-DD 23:59:59')
    } else if (chooseDate.value === '月') {
      formParams.value.startDate = moment(settlementDate.value)
        .startOf('month')
        .format('YYYY-MM-DD HH:mm:ss')
      formParams.value.endDate = moment(settlementDate.value)
        .endOf('month')
        .format('YYYY-MM-DD HH:mm:ss')
    }
  } else {
    ElMessage({
      message: '请选择具体时间',
      type: 'warning',
      duration: 2000,
    })
    return
  }

  const params = Object.assign({}, formParams.value)

  const res1 = await http.post('/Statistic/Overview/Part1', params) //付费病例
  Object.assign(userInfo, res1.data)
  const res2 = await http.post('/Statistic/Overview/Part2', params) // 医疗费用分析
  console.log(res2)
  lineList1.value.legend = res2.data.line1?.legend || []
  lineList1.value.xAxis = res2.data.line1?.xAxis || []
  lineList1.value.series[0].data = res2.data.line1?.series[0].datas || []
  lineList1.value.series[1].data = res2.data.line1?.series[1].datas || []

  lineList2.value.legend = res2.data.line2?.legend || []
  lineList2.value.xAxis = res2.data.line2?.xAxis || []
  lineList2.value.series[0].data = res2.data.line2?.series[0].datas || []
  lineList2.value.series[1].data = res2.data.line2?.series[1].datas || []
  lineList2.value.series[2].data = res2.data.line2?.series[2].datas || []

  // lineList2.value = res.data.line2 || { legend: [], xAxis: [], series: [] }
  lineList3.value.data = res2.data.pie || []
  lineList3.value.legend = res2.data.pie.map((item) => item.name) || []
  // lineList4.value = res.data.line4 || { xAxis: [], legend: [], series: [] }

  const res3 = await http.post('/Statistic/Overview/Part3', params) // 医疗服务能力评价
  // totalData.value = res.data.top1 || []

  const res4 = await http.post('/Statistic/Overview/Part4', params) // 服务效率评价
  const res5 = await http.post('/Statistic/Overview/Part5', params) // 医疗安全相关评价
  updateLine1Chart()
  updateLine2Chart()
  updateLine3Chart()
  updateLine4Chart()
  updateLine5Chart()
  updateLine6Chart()
  updateLine7Chart()
  updateLine8Chart()
  updateLine9Chart()
  updateLine10Chart()
  updateLine11Chart()
  updateLine12Chart()
}
onActivated(() => {
  settlementDate.value = moment().startOf('year').format('YYYY-MM-DD HH:mm:ss')
  goSearch()
})

window.addEventListener('resize', () => {
  lineChart1?.resize()
  lineChart2?.resize()
  lineChart3?.resize()
  lineChart4?.resize()
  lineChart5?.resize()
  lineChart6?.resize()
  lineChart7?.resize()
  lineChart8?.resize()
  lineChart9?.resize()
  lineChart10?.resize()
  lineChart11?.resize()
  lineChart12?.resize()
})

onBeforeUnmount(() => {
  lineChart1?.dispose()
  lineChart2?.dispose()
  lineChart3?.dispose()
  lineChart4?.dispose()
  lineChart5?.dispose()
  lineChart6?.dispose()
  lineChart7?.dispose()
  lineChart8?.dispose()
  lineChart9?.dispose()
  lineChart10?.dispose()
  lineChart11?.dispose()
  lineChart12?.dispose()
})
</script>

<style lang="less" scoped>
.chart-container {
  display: flex;
  justify-content: space-between;
}
.chart-header {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.ivu-card {
  min-height: 127.5px;
}
.el-date-range-picker {
  width: 680px !important;
}
.el-date-range-picker .el-picker-panel__body {
  min-width: 640px;
}

.custom-year-cell {
  padding: 4px;
  text-align: center;
}

.cell-buttons {
  display: flex;
  gap: 4px;
  justify-content: center;
  margin-top: 4px;
}

.cell-buttons .el-button {
  flex: 1;
  min-width: 60px;
}

/* 调整日期选择器的宽度以适应按钮 */
.el-picker-panel {
  min-width: 200px !important;
}

.half-year-cell {
  padding: 8px 0;
  text-align: center;
}

.year-text {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.half-year-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
}

.half-year-buttons .el-button {
  flex: 1;
  margin: 0;
  padding: 4px 0;
}

.half-year-buttons .divider {
  width: 1px;
  height: 16px;
  background-color: #dcdfe6;
  margin: 0 4px;
}

.half-year-buttons .active {
  color: var(--el-color-primary);
  font-weight: bold;
}

/* 调整日期选择器的宽度 */
.el-picker-panel.el-date-picker {
  min-width: 280px !important;
}

.el-year-table td {
  padding: 8px 0;
}

.el-table {
  margin-top: 20px;
}
.el-table th {
  background-color: #f5f7fa;
}
</style>
